<?php
/**
 * 后台Admin模块 课程表管理功能
 */
#定义命名空间
namespace Admin\Controller;
class CourseController extends ComController{
    
    /**
     * 发布过的课程列表 
     */
    public function index(){
        $sc_id = session('sc_id');//学校id
        $course = M('course');//实例化课程主表
        $class = M('class');//实例化班级表
        $prefix = C('DB_PREFIX');//读取数据表的前缀
        //搜索
        $class_id = I('class_id') ? I('class_id') : 0; //班级
        $time = I('order') ? I('order') : 'asc';//发布时间
        if($class_id) $where["{$prefix}course.class_id"] = $class_id;
        $where["{$prefix}course.sc_id"] = $sc_id;
        $count_where['sc_id'] = $sc_id;
        // $where["{$prefix}course.is_del"] = 1;
        $p = I('get.p') ? I('get.p') : 1;//接收页数
        $pagesize = 15;//每页显示条数
        $offset = ($p-1)*$pagesize; //偏移量
        $order = "  {$prefix}course.add_time {$time}";//排序
        $count = $course
                 ->where($count_where)
                 ->limit($offset.','.$pagesize)
                 ->count();//总条数
        $course_info = $course
                ->field("{$prefix}course.*,{$prefix}class.name as class_name")
                ->join("inner join {$prefix}class on {$prefix}class.id = {$prefix}course.class_id")
                ->where($where)->order($order)
                ->select();
        $data = array();
        foreach ($course_info as $k => $v) {
            $data[$k]['id'] = $v['id'];
            $data[$k]['class_name'] = $v['class_name'];
            $data[$k]['title'] = $v['title'];
            $data[$k]['is_del'] = $v['is_del'];
            $data[$k]['add_time'] = $v['add_time'];
            $se = $this->getSe($v['id']);
            $data[$k]['start'] = $se['start'];
            $data[$k]['end'] = $se['end'];
        }
        $page = new \Think\Page($count,$pagesize);
        $page = $page->show();
        $class_info = $class->where(array('sc_id'=>$sc_id))->select();
        $this->assign('class',$class_info);
        $this->assign('page',$page);
        $this->assign('data',$data);

        $this->display();
    }

    /**
     * 通过课程ID获取 本周课程开始时间-结束时间
     */
    public function getSe($id = 0){
        $course_datetime = M('course_datetime');
        $prefix = C('DB_PREFIX');//读取数据表的前缀
        $data = $course_datetime->field("Min({$prefix}course_datetime.time) as start ,Max({$prefix}course_datetime.time) as end")->where(' course_id ='.$id)->find();
        if($data) return $data;
        else return array('start'=>0,'end'=>0);
    }

    /**
     * 发布课程表 post
     */
    public function append(){
        $sc_id = session('sc_id'); //学校id
        if(IS_POST){
            $course_datetime = M('course_datetime');//实例化课程表外链表
            $prefix = C('DB_PREFIX');//读取数据表的前缀
            //接收传递的参数
            $param = I('post.');
            $class_id = $param['class_id'] ? $param['class_id'] : 0;
            $title = $param['title'] ? $param['title'] : '';
            $time = $param['time'] ? $param['time'] : '';
            $morning = $param['morning'] ? $param['morning'] : '';
            $afternoon = $param['afternoon'] ? $param['afternoon'] : '';
            //处理中英文逗号，
            $morning = str_replace('，', ',', $morning);
            $afternoon = str_replace('，', ',', $afternoon);
            //时间 暂定
            $newTime = array();
            foreach ($time as $key => $value) {
                $strTime = explode('-', $value);
                $newTime[] = strtotime($strTime[0]);
            }
            // 验证
            if(!$class_id){
                $this->error('请选择班级!');
            }
            if(!$title){
                $this->error('请添加标题!');
            }
            if(empty($time) && !is_array($time)){
                $this->error('请填写时间!');
            }
            if(empty($morning) && !is_array($morning)){
                $this->error('上午课程必须填写!');
            }else{
               foreach($morning as $key => $value) {
                    if(empty($value)){
                        $this->error('上午课程必须填写!');
                        break;
                    }
                } 
            }
            if(empty($afternoon) && !is_array($afternoon)){
                $this->error('下午课程必须填写!');
            }else{
                foreach($afternoon as $key => $value) {
                    if(empty($value)){
                        $this->error('下午课程必须填写!');
                        break;
                    }
                }
            }
            
            $isExt = $course_datetime
                    ->join("inner join {$prefix}course on {$prefix}course_datetime.course_id = {$prefix}course.id")
                    ->where(array("{$prefix}course.sc_id"=>$sc_id,"{$prefix}course.class_id"=>$class_id,"{$prefix}course_datetime.time"=>array("in",$newTime)))->find(); //验证该班级下本周是否已经发布了课程
            if($isExt){
                $this->error('本周已经发布课程，不能重复发布!');
            }
            //插入课程主表
            $course_data['class_id'] = $class_id;
            $course_data['title'] = $title;
            $course_data['sc_id'] = $sc_id;
            $course_data['add_time'] = time();
            $course = M('course');
            $course_res = $course->add($course_data);
            if($course_res){
                $data = array(); //组装数据 添加课程外链表信息
                foreach ($time as $k => $v) {
                    $data[$k]['sc_id'] = $sc_id;
                    $data[$k]['course_id'] = $course_res;
                    $data[$k]['morning'] = $morning[$k];
                    $data[$k]['time'] = $newTime[$k];
                    $data[$k]['afternoon'] = $afternoon[$k];
                    $data[$k]['add_time'] = time();
                 }
                 $course_datatime_res = $course_datetime->addAll($data);
                 if($course_datatime_res){
                    $this->error('添加成功!',U('index'));
                 }else{
                    //添加失败
                    //删除课程主表对应信息
                    $course->where(array('id'=>$course_res))->delete();
                    echo $course_datetime->getError();die;
                    $this->error('添加失败!');

                 }
            }else{
                $this->error('添加失败!');
            }
        }else{
            //展示页面
            $class = M('class'); //实例化班级表
            $where['sc_id'] = $sc_id;
            $where['is_del'] = 1;//未删除班级
            $class_info = $class->where($where)->select();
            $this->assign('class',$class_info);
            $this->assign('form_url',U('append'));
            $this->display('append');
        }
    }

    /**
     * 根据课程id 修改课程表
     * @param   $id 课程表主键id
     */
    public function edit(){
        $sc_id = session('sc_id');//获取当前学校id
        $id = I('get.id') ? I('get.id') : 0;
        $course = M('course');//课程主表
        $course_datetime = M('course_datetime');//课程外链表
        $class = M('class');//班级表
        if(IS_POST){
            //接收参数
            $param = I('post.');
            $title = $param['title'] ? $param['title'] : '';
            $morning = $param['morning'] ? $param['morning'] : array();
            $afternoon = $param['afternoon'] ? $param['afternoon'] : array();
            $course_id = $param['id'] ? $param['id'] : 0;
            //处理中英文逗号，
            $morning = str_replace('，', ',', $morning);
            $afternoon = str_replace('，', ',', $afternoon);
            if(!$title){
                $this->error('请添加标题!');
            }
            if(empty($morning) && !is_array($morning)){
                $this->error('上午课程必须填写!');
            }else{
               foreach($morning as $key => $value) {
                    if(empty($value)){
                        $this->error('上午课程必须填写!');
                        break;
                    }
                } 
            }
            if(empty($afternoon) && !is_array($afternoon)){
                $this->error('下午课程必须填写!');
            }else{
                foreach($afternoon as $key => $value) {
                    if(empty($value)){
                        $this->error('下午课程必须填写!');
                        break;
                    }
                }
            }
            //更新 课程主表
            $course_data['title'] = $title;
            $course_data['update_time'] = time();
            $course_res = $course->where(array('id'=>$course_id))->save($course_data);
            $cd_list = $course_datetime->where(array('course_id'=>$course_id))->order(' id ')->select();
            $cd_ids = array();//课程外链表id
            foreach ($cd_list as $key => $value) {
                $cd_ids[] = $value['id'];
            }
            //更新 课程外链表
            $course_datetime_data = array();
            foreach ($afternoon as $k => $v) {
                $course_datetime_data[$k]['afternoon'] = $afternoon[$k];
                $course_datetime_data[$k]['morning'] = $morning[$k];
                $course_datetime_data[$k]['update_time'] = time();
            }
            foreach ($cd_ids as $key => $value) {
                $course_datetime->where('id ='.$value)->save($course_datetime_data[$key]);
            }
            $this->success('修改成功!');
        }else{ 
            if($id){
                $where["id"] = $id;
                $where["sc_id"] = $sc_id;
                $course_info = $course->where($where)->find();
                //组装数据
                //获取课程表主键id
                $course_time = $course_datetime->where(array('course_id'=>$id))->select();
                if($course_info && $course_time){

                    $course_info['datetime'] = $course_time;
                    $class_info = $class->where(' is_del = 1 and sc_id = '.$sc_id)->select();
                    $this->assign('class',$class_info);
                    $this->assign('data',$course_info);
                    $this->display();
                }else{
                    $this->error('没有数据!',U('index'));
                }
            }else{
                $this->error('缺少参数!',U('index'));
            }
        }
    }

    /**
     * 根据课程id 删除课程表
     * @param int $id 课程表主键id
     */
    public function del(){
        $id = I('get.id') ? I('get.id') : 0;//获取id
        if($id){
            $course = M('course');
            $course_datetime = M('course_datetime');
            $course_data= $course->where('id = '.$id)->find();//实例化课程主表
            if($course_data){
                $course_res = $course->where(' id = '.$id)->delete();
                $course_datetime_res = $course_datetime->where(' course_id = '.$id)->delete();
                if($course_res && $course_datetime_res){
                    $this->error('删除成功!',U('index'));
                }else{
                    $this->error('删除失败!',U('index'));
                }
            }else{
                $this->error('数据不存在!',U('index'));
            }
        }else{
            $this->error('缺少参数!',U('index'));
        }
    }

    /**
     * ajax修改显示状态
     * @param string $is_show 课程表主键id-状态
     */
    public function is_show(){
        $param = I('post.is_show') ? I('post.is_show') : 0;//获取id
        $param = explode('-', $param);
        $is_show = $param['1'];
        $id = $param['0'];
        if($id){
            $course = M('course');
            $course_data= $course->where('id = '.$id)->find();//实例化课程主表
            if($course_data){
                $course_res = $course->where(' id = '.$id)->save(array('is_del'=>$is_show));
                if($course_res !== false){
                    echo json_encode(array('res'=>1,'msg'=>'成功'));
                }else{
                    echo json_encode(array('res'=>0,'msg'=>'失败'));
                }
            }else{
                echo json_encode(array('res'=>0,'msg'=>'失败'));
            }
        }else{
            echo json_encode(array('res'=>0,'msg'=>'失败'));
        }
    }

    /**
     * 根据课程id 查看课程详情
     * @param int $id 
     */
    public function detail(){
        $id = I('get.id') ? I('get.id') : 0;//获取id
        $sc_id = session('sc_id');//学校id
        if($id){
                $course = M('course');//课程主表
                $course_datetime = M('course_datetime');//课程外链表
                $class = M('class');//班级表
                $where["id"] = $id;
                $course_info = $course->where($where)->find();
                //组装数据
                //获取课程表主键id
                $course_time = $course_datetime->where(array('course_id'=>$id))->select();
                if($course_info && $course_time){

                    $course_info['datetime'] = $course_time;
                    $class_info = $class->where('sc_id = '.$sc_id)->select();
                    $this->assign('class',$class_info);
                    $this->assign('data',$course_info);
                    $this->display();
                }else{
                    $this->error('没有数据!');
                }
            }else{
                $this->error('缺少参数!',U('index'));
            }
    }
}